/**
 * http 模块 + url 模块结合做一个 简单的路由判断，和登录接受参数
 * @type {module:http}
 */
var http = require('http');
var httpServer_url = require('url');
var fs = require('fs');
var querystring = require('querystring');
// 创建服务
var server = http.createServer();
var htmlDir = __dirname + '/tpl/'
// 请求
server.on('request', (req, res)=>{

    console.log('req.url', req.url)
    var urlStr = httpServer_url.parse(req.url)


    switch (urlStr.pathname) {
        case '/':  //这是首页
            sendData(htmlDir + 'index.html',req, res)
            break;
        case '/login':  // 这是user页面
            sendData(htmlDir + 'login.html',req, res)
            break;
        case '/login/check':  // 登录提交验证
            console.log('urlStr', urlStr)
            if(req.method.toUpperCase() === 'GET'){
                console.log('get 请求提交的参数', querystring.parse(urlStr.query))
            }else if(req.method.toUpperCase() === 'POST'){
                console.log('post')
                let rawData = '';

                req.on('data', (chunk) => {
                    rawData += chunk;
                });

                req.on('end', () => {
                    console.log('post请求提交的参数:',rawData)
                    console.log('post请求提交的参数格式化以后:',querystring.parse(rawData))
                });
            }

            break;
        default:
            // 做重定向, 跳转到首页
            console.log('http.STATUS_CODES', http.STATUS_CODES)
            res.writeHead(301, http.STATUS_CODES[301], {
                'Conttent-Type': 'text/html;charset=utf8',
                'Location': '/'
            })
            res.end()

            // 或者直接显示404页面
            // sendData(htmlDir + '404.html',req, res)
            break;

    }
    // console.log(urlStr)
    // console.log(req.method)
})

// fs 读取页面模板
function sendData(filePath, req, res){
    fs.readFile(filePath, (err, data)=>{
        if(err){
            res.writeHead(404, {'content-type': 'text/html;charset=utf-8'});
            res.end('404错误')
        }else{
            res.writeHead(200, {'content-type': 'text/html;charset=utf-8'});
            res.end(data)
        }
    })
}


// 监听端口
server.listen(8088, 'localhost')